package com.xnyzc.lhy.didi.service.impl.xiecheng;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.component.amap.GouldMapUtils;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MqConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.GouldResult;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.global.Configuration;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.cms.EVehicleType;
import com.xnyzc.lhy.common.penum.order.EOrderChannelType;
import com.xnyzc.lhy.common.penum.order.EOrderStatus;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.DateUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.LuckDrawUtil;
import com.xnyzc.lhy.common.util.http.HttpRequestUtil;
import com.xnyzc.lhy.didi.common.constants.EXieChengCallVehType;
import com.xnyzc.lhy.didi.common.constants.EXieChengResponseConstant;
import com.xnyzc.lhy.didi.common.constants.EXieChengVehicleType;
import com.xnyzc.lhy.didi.entity.billGroup.OaSysBillRuleGroup;
import com.xnyzc.lhy.didi.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.didi.entity.param.other.OrderInfoCreated;
import com.xnyzc.lhy.didi.entity.param.other.StatisticalData;
import com.xnyzc.lhy.didi.entity.param.xiecheng.request.*;
import com.xnyzc.lhy.didi.entity.param.xiecheng.response.*;
import com.xnyzc.lhy.didi.entity.price.OaSysBillSpecialSceneRule;
import com.xnyzc.lhy.didi.mapper.billGroup.OaSysBillRuleGroupMapper;
import com.xnyzc.lhy.didi.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.didi.mapper.order.OaDOrderMapper;
import com.xnyzc.lhy.didi.mapper.price.OaSysBillSpecialSceneRuleMapper;
import com.xnyzc.lhy.didi.mapper.price.OaSysPlatformTimeRuleMapper;
import com.xnyzc.lhy.didi.mapper.sys.OaSysOfficeMapper;
import com.xnyzc.lhy.didi.mapper.xiecheng.CityInfoMapper;
import com.xnyzc.lhy.didi.mapper.xiecheng.VehicleInfoMapper;
import com.xnyzc.lhy.didi.mq.MQProducer;
import com.xnyzc.lhy.didi.service.xiecheng.EmbargoAreaService;
import com.xnyzc.lhy.didi.service.xiecheng.XcPriceService;
import com.xnyzc.lhy.didi.service.xiecheng.XcRequsetService;
import com.xnyzc.lhy.didi.tongcheng.entity.param.order.TcOrderPriceParam;
import com.xnyzc.lhy.didi.tongcheng.penum.ETongChengRideType;
import com.xnyzc.lhy.didi.util.XieChengUtil;
import com.xnyzc.lhy.mis.entity.platform.OaSysPlatformTimeControl;
import com.xnyzc.lhy.mis.entity.system.*;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.order.entity.order.OaDOrder;
import com.xnyzc.lhy.order.entity.sidebar.OaSysOffice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class XcRequestServiceImpl implements XcRequsetService {

    //供应商ID
    @Value("${global.xc.venderId}")
    private String venderId;

    //渠道
    @Value("${global.xc.channel}")
    private String channel2;

    //版本
    @Value("${global.xc.version}")
    private String version;

    //携程密钥
    @Value("${global.xc.secretKey}")
    private String secretKey;

    @Value("${global.xc.callback}")
    private String callback;

    @Autowired
    private RedisCommon redisCommon;
    @Autowired
    private XcPriceService xcPriceService;
    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;
    @Autowired
    private CityInfoMapper cityInfoMapper;
    @Autowired
    private VehicleInfoMapper vehicleInfoMapper;
    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;
    @Autowired
    private MQProducer producer;
    @Autowired
    private OaDOrderMapper oaDOrderMapper;
    @Autowired
    private OaSysPlatformTimeRuleMapper oaSysPlatformTimeRuleMapper;
    @Autowired
    private EmbargoAreaService embargoAreaService;
    @Autowired
    private OaSysBillRuleGroupMapper oaSysBillRuleGroupMapper;
    @Autowired
    private OaSysBillSpecialSceneRuleMapper oaSysBillSpecialSceneRuleMapper;

    private Integer channel = EOrderChannelType.xiecheng.getType();

    @Autowired
    private XcOrderStatusSyncServiceImpl orderStatusSyncService;

    @Override
    public XieChengResponse queryProduct(QueryProductRequest request) throws ParseException {
        long startTime = new Date(System.currentTimeMillis()).getTime();
        //验证平台时间控制是否接单
        try {
            if (verificationTime(request)) {
                return XieChengResponse.error(EXieChengResponseConstant.RROR_EARLY);
            }
        } catch (ParseException e) {
            log.info("验证平台时间 查价异常--->" + e.getMessage());
        }
        //携程  高德采用线路策略10-->返回结果会躲避拥堵，路程较短，尽量缩短时间，与高德地图的默认策略也就是不进行任何勾选一致
        //携程  高德采用线路策略0-->速度优先，不考虑当时路况，此路线不一定距离最短
        GouldResult.RouteBean router = GouldMapUtils.getStrategyXC(0, request.getDuseLocation().getLongitude() + "," + request.getDuseLocation().getLatitude(), request.getAuseLocation().getLongitude() + "," + request.getAuseLocation().getLatitude());
        if (router == null) {
            return XieChengResponse.error();
        }
        List<Long> vehicleTypes = request.getVehicleTypeList();
        if (vehicleTypes == null) {
            vehicleTypes = new ArrayList<>(4);
            vehicleTypes.add(EXieChengVehicleType.vehTypeEconomic.getCode());
            vehicleTypes.add(EXieChengVehicleType.vehTypeComfortable.getCode());
            //2021-05-18 全面打开携程豪华车车型接单
            vehicleTypes.add(EXieChengVehicleType.vehTypeLuxury.getCode());
            vehicleTypes.add(EXieChengVehicleType.vehTypeBusiness.getCode());
        }
        Date startDate = DateUtil.convertStringToDate(request.getUseTime(), "yyyy-MM-dd HH:mm");
        int callType = EXieChengCallVehType.getByCode(request.getCategoryCode()).getType();
        String cityCode = getCityIdByCode(request.getFixedLocation().getCityId());

        if (cityCode == null) {
            return XieChengResponse.error();
        }
        //询价的起点和终点
        String origin = request.getAuseLocation().getDetailAddress();
        String destination = request.getDuseLocation().getDetailAddress();
        // 判断起点、终点是否处在禁运区域
        HashMap<Object, Object> flagMap = verifyAreaCode(router, cityCode, callType, channel, origin, destination);//同程channel是2
        List<NewBillRules> newBillRules = (List<NewBillRules>) flagMap.get("rules");
        HashMap<String, String> mprices = new HashMap<>(8);
        List<ShoppingQueryProductDTO> prices = new ArrayList<>();

        long appointment = DateUtil.getStringDateTime(request.getUseTime(), "yyyy-MM-dd HH:mm");
        long appointmentDay = DateUtil.getStringDateTime(request.getUseTime(), "yyyy-MM-dd");
        Date cDateHour = DateUtil.getDateHourShort(startTime);
        //精确到小时的预约时间
        Date aDateHour = DateUtil.getDateHourShort(appointment);
        HashMap<Integer, Integer> staticalPriceMap = new HashMap<>();
        StatisticalData statisticalData = StatisticalData.builder()
                .cityCode(cityCode).channel(channel)
                .origin(origin).destination(destination).callType(callType)
                .startLng(request.getAuseLocation().getLongitude().doubleValue())
                .startLat(request.getAuseLocation().getLatitude().doubleValue())
                .endLng(request.getDuseLocation().getLongitude().doubleValue())
                .endLat(request.getDuseLocation().getLatitude().doubleValue())
                .appointmentTime(appointment).timestamp(startTime)
                .build();

        for (Long vehicleType : vehicleTypes) {
            EVehicleType mvehicleType = EXieChengVehicleType.getByType(vehicleType.intValue());
            if (mvehicleType == null) {
                continue;
            }
            RulesParam rulesParam = new RulesParam();
            NewBillRules billRules = newBillRules.get(0);
            Double premium = billRules.getPremium();
            Integer drawRatio = billRules.getDrawRatio();
            List<RulesParam> fees = billRules.getFees();
            for (int i = 0; i < fees.size(); i++) {
                if (mvehicleType.getValue() == fees.get(i).getVehicleType().longValue()
                        && CheckUtil.objIsNotEmpty(fees.get(i).getBillRules())) {
                    rulesParam = fees.get(i);
                    break;
                }
            }
            if (CheckUtil.objIsEmpty(rulesParam.getBillRules())) {
                continue;
            }
            String ruleId = newBillRules.get(0).getRuleId().toString();
            Integer robable = newBillRules.get(0).getRobable();
            robable = robable == null ? 0 : robable;
            //判断禁运情况，如果命中禁运区域，直接进入下次循环
            if (flagMap.containsKey(mvehicleType.getValue()) && (Integer) flagMap.get(mvehicleType.getValue()) == 1) {//1说明命中
                continue;
            }
            HashMap<String, Object> priceMap = xcPriceService.getPriceDetail(channel, cityCode, mvehicleType, callType,
                    startDate, router, rulesParam, ruleId, robable, premium, drawRatio);
            if (priceMap == null) {
                long responseTime = new Date(System.currentTimeMillis()).getTime() - startTime;
                statisticalData.setResponseTime(responseTime);
                //将orderPriceParam发送到mq中
                producer.sendMsg(statisticalData, MqConstant.DATA_PRICE_STATISTICAL, null, 1);
                return XieChengResponse.error(EXieChengResponseConstant.ERROR_LOCATION);
            }
            String estimateId = priceMap.get("estimateId").toString();
            String estDistance = priceMap.get("estDistance").toString();
            redisCommon.setHashMap(priceMap.get("estimateId").toString(), priceMap, Long.valueOf(86400));
            mprices.put(String.valueOf(vehicleType), estimateId);

            BigDecimal totalFee = getFee(priceMap, "totalFee");

            ShoppingQueryProductDTO shopping = new ShoppingQueryProductDTO();
            shopping.setVehicleType(vehicleType);
            shopping.setPrice(totalFee);
            prices.add(shopping);
            staticalPriceMap.put(vehicleType.intValue(), totalFee.intValue());
            statisticalData.setMilage(new BigDecimal(estDistance).intValue());
        }
        if (CheckUtil.collectionIsEmpty(prices)) {
            return XieChengResponse.error(EXieChengResponseConstant.ERROR_LOCATION);
        }
        //保存价格关键字集合
        String estimateId = String.valueOf(IDUtil.nextId());
        redisCommon.setHashMap(RedisPrefixConstant.DIDI_ESTIMATE + estimateId, mprices, Long.valueOf(86400));

        QueryProductResponse response = new QueryProductResponse();
        response.wrap(EXieChengResponseConstant.OK);
        response.setPriceMark(estimateId);
        response.setCurrency("CNY");
        response.setQueryResultList(prices);
        statisticalData.setPriceMarker(estimateId);
        long responseTime = new Date(System.currentTimeMillis()).getTime() - startTime;
        statisticalData.setResponseTime(responseTime);
        String priceStr = JSON.toJSONString(staticalPriceMap);
        statisticalData.setPrices(priceStr);
        //将orderPriceParam发送到mq中
        producer.sendMsg(statisticalData, MqConstant.DATA_PRICE_STATISTICAL, null, 1);
        return response;
    }

    /**
     * 查价验证平台时间控制是否接单
     *
     * @param request
     * @return
     */
    private Boolean verificationTimeByQPrice(QueryProductRequest request) throws ParseException {

        /*String cityCode = getCityIdByCode(request.getFixedLocation().getCityId());
        QueryWrapper<OaSysPlatformTimeControl> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysPlatformTimeControl.CHANNEL_ID, channel);
        queryWrapper.eq(OaSysPlatformTimeControl.CITY_ID, cityCode);
        queryWrapper.eq(OaSysPlatformTimeControl.DELETED, 0);

        List<OaSysPlatformTimeControl> platformTimeControlList = oaSysPlatformTimeRuleMapper.selectList(queryWrapper);
        if (CheckUtil.objIsEmpty(platformTimeControlList)) {
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        //用车时间
        Date startDate = DateUtil.convertStringToDate(request.getUseTime(), "yyyy-MM-dd HH:mm");
        Calendar useCalendar = Calendar.getInstance();
        useCalendar.setTime(startDate);
        //获取用车时间的号数
        //int day = useCalendar.get(Calendar.DAY_OF_MONTH);
        double day = useCalendar.getTimeInMillis() / (3600 * 24 * 1000D);
        //获取当前时间的号数
        Calendar curCalendar = Calendar.getInstance();
        curCalendar.setTime(new Date());
        //int curDay = curCalendar.get(Calendar.DAY_OF_MONTH);
        double curDay = curCalendar.getTimeInMillis() / (3600 * 24 * 1000D);

        //相差天数
        double differDay = day - curDay;
        if (differDay < 0) {//过时直接拒绝
            return true;
        }
        long useTime = useCalendar.get(Calendar.HOUR_OF_DAY) * 60 + useCalendar.get(Calendar.MINUTE);// tmpTime/(1000*60);
        //请求时间
        Date timestamp = new Date(System.currentTimeMillis());
        Calendar timestampCalendar = Calendar.getInstance();
        timestampCalendar.setTime(timestamp);
        int timestampTime = timestampCalendar.get(Calendar.HOUR_OF_DAY) * 60 + timestampCalendar.get(Calendar.MINUTE);

        for (OaSysPlatformTimeControl info : platformTimeControlList) {
            if (info.getUseFullTime() == 0) {//使用全时就false-->优先判断
                return false;
            } else {
                //开始时间
                Calendar startTime = Calendar.getInstance();
                startTime.setTime(sdf.parse(info.getStartTime()));
                int start = startTime.get(Calendar.HOUR_OF_DAY) * 60 + startTime.get(Calendar.MINUTE);

                //结束时间
                Calendar endTime = Calendar.getInstance();
                endTime.setTime(sdf.parse(info.getEndTime()));
                int end = endTime.get(Calendar.HOUR_OF_DAY) * 60 + endTime.get(Calendar.MINUTE);

                //延长时间
                int delayTime = Integer.parseInt(info.getDelayTime());
                //判断方式为：开始时间≤请求提交时间 ≤结束时间 and 用车时间≤(结束时间（当日）+临近时间长度) == true，即拒绝服务
                if ((start <= timestampTime && timestampTime <= end) && (differDay * 24 * 60) + useTime <= (end + delayTime)) {
                    return true;
                }
            }
        }
        return false;*/
        String cityCode = getCityIdByCode(request.getFixedLocation().getCityId());
        // FIXME 删除手动转码 海口127-460100 上海321-310100
        if ("127".equals(cityCode)) {
            cityCode = "460100";
        }
        if ("321".equals(cityCode)) {
            cityCode = "310100";
        }
        //用车时间
        Date useDate = DateUtil.convertStringToDate(request.getUseTime(), "yyyy-MM-dd HH:mm");
        String currtDay = DateUtil.getStringDateShort(new Date()); //获取当前时间的yyyy-MM-dd年月日格式
        String useDay = DateUtil.convertToStringCustom(useDate, "yyyy-MM-dd HH:mm"); //获取用车时间的yyyy-MM-dd年月日格式

        //从redis查询
        String redisStr = redisCommon.getStr(RedisPrefixConstant.PLATFORM_TIME_RULE + channel + "_" + cityCode);
        OaSysPlatformTimeControl oaSysPlatformTimeControl = JSON.parseObject(redisStr, OaSysPlatformTimeControl.class);
        if (CheckUtil.objIsEmpty(oaSysPlatformTimeControl)) {
            //redis中查不到 查数据库
           /* OaSysPlatformTimeControl osp =  oaSysPlatformTimeRuleMapper.selectTimeByConditions(channel,cityCode,useDate,currtDay,useDay);
            if(CheckUtil.objIsNotEmpty(osp)){
                OaSysPlatformTimeControl newRule = new OaSysPlatformTimeControl();
                newRule.setControlId(IDUtil.nextId());
                newRule.setCityId(osp.getCityId());
                newRule.setChannelId(osp.getChannelId());
                newRule.setGroupId(osp.getGroupId());
                newRule.setCompanyId(osp.getCompanyId());
                newRule.setChannelName(osp.getChannelName());
                newRule.setUseFullTime(osp.getUseFullTime());
                newRule.setStartTime(osp.getStartTime());
                newRule.setEndTime(osp.getEndTime());
                newRule.setDelayTime(osp.getDelayTime());
                newRule.setCreateTime(osp.getCreateTime());
                newRule.setCreateUser(osp.getCreateUser());
                newRule.setUpdateUser(osp.getUpdateUser());
                newRule.setUpdateTime(osp.getUpdateTime());
                newRule.setDeleted(0);
                redisCommon.set(RedisPrefixConstant.PLATFORM_TIME_RULE+channel+"_"+cityCode,JSON.toJSONString(newRule));
                return true;
            }*/
            return false;
        }
        if (oaSysPlatformTimeControl.getUseFullTime() == 0) {
            //使用全时就false-->优先判断
            return false;
        }
        long delayTime = Integer.parseInt(oaSysPlatformTimeControl.getDelayTime()) * 60 * 1000L;
        //组装当前日期年月日和限制的时分
        long currStartTime = DateUtil.convertStringToDate(currtDay + " " + oaSysPlatformTimeControl.getStartTime(), "yyyy-MM-dd HH:mm").getTime();
        long currEndTime = DateUtil.convertStringToDate(currtDay + " " + oaSysPlatformTimeControl.getEndTime(), "yyyy-MM-dd HH:mm").getTime();
        //预约用车时间
        long useTimestamp = useDate.getTime();
        // 限制的开始时间 <= 订单用车时间 <= 限制的结束时间 用车时间在限制时间范围内则返回true
        if (useTimestamp >= currStartTime && useTimestamp <= currEndTime + delayTime) {
            return true;
        }
        return false;
    }

    /**
     * 查价验证平台时间控制
     *
     * @param request
     * @return
     */
    private Boolean verificationTime(QueryProductRequest request) throws ParseException {

        String cityCode = getCityIdByCode(request.getFixedLocation().getCityId());
        // FIXME 删除手动转码 海口127-460100 上海321-310100
        if ("127".equals(cityCode)) {
            cityCode = "460100";
        }
        if ("321".equals(cityCode)) {
            cityCode = "310100";
        }
        //用车时间
        Date useDate = DateUtil.convertStringToDate(request.getUseTime(), "yyyy-MM-dd HH:mm");
        String currtDay = DateUtil.getStringDateShort(new Date()); //获取当前时间的yyyy-MM-dd年月日格式
        String useDay = DateUtil.convertToStringCustom(useDate, "yyyy-MM-dd HH:mm"); //获取用车时间的yyyy-MM-dd年月日格式

        //从redis查询
        String redisStr = redisCommon.getStr(RedisPrefixConstant.PLATFORM_TIME_RULE + channel + "_" + cityCode);
        OaSysPlatformTimeControl oaSysPlatformTimeControl = JSON.parseObject(redisStr, OaSysPlatformTimeControl.class);
        if (CheckUtil.objIsEmpty(oaSysPlatformTimeControl)) {
            //redis中查不到 查数据库
           /* OaSysPlatformTimeControl osp =  oaSysPlatformTimeRuleMapper.selectTimeByConditions(channel,cityCode,useDate,currtDay,useDay);
            if(CheckUtil.objIsNotEmpty(osp)){
                OaSysPlatformTimeControl newRule = new OaSysPlatformTimeControl();
                newRule.setControlId(IDUtil.nextId());
                newRule.setCityId(osp.getCityId());
                newRule.setChannelId(osp.getChannelId());
                newRule.setGroupId(osp.getGroupId());
                newRule.setCompanyId(osp.getCompanyId());
                newRule.setChannelName(osp.getChannelName());
                newRule.setUseFullTime(osp.getUseFullTime());
                newRule.setStartTime(osp.getStartTime());
                newRule.setEndTime(osp.getEndTime());
                newRule.setDelayTime(osp.getDelayTime());
                newRule.setCreateTime(osp.getCreateTime());
                newRule.setCreateUser(osp.getCreateUser());
                newRule.setUpdateUser(osp.getUpdateUser());
                newRule.setUpdateTime(osp.getUpdateTime());
                newRule.setDeleted(0);
                redisCommon.set(RedisPrefixConstant.PLATFORM_TIME_RULE+channel+"_"+cityCode,JSON.toJSONString(newRule));
                return true;
            }*/
            return false;
        }
        if (oaSysPlatformTimeControl.getUseFullTime() == 0) {
            //使用全时就false-->优先判断
            return false;
        }
        long delayTime = Integer.parseInt(oaSysPlatformTimeControl.getDelayTime()) * 60 * 1000L;
        //组装当前日期年月日和限制的时分
        long currStartTime = DateUtil.convertStringToDate(currtDay + " " + oaSysPlatformTimeControl.getStartTime(), "yyyy-MM-dd HH:mm").getTime();
        long currEndTime = DateUtil.convertStringToDate(currtDay + " " + oaSysPlatformTimeControl.getEndTime(), "yyyy-MM-dd HH:mm").getTime();
        //预约用车时间
        long useTimestamp = useDate.getTime();
        // 限制的开始时间 <= 订单用车时间 <= 限制的结束时间 用车时间在限制时间范围内则返回true
        if (useTimestamp >= currStartTime && useTimestamp <= currEndTime + delayTime) {
            return true;
        }
        return false;
    }


    /**
     * 创建订单验证平台时间控制是否接单
     *
     * @param request
     * @return
     */
    private Boolean verificationTimeByCPrice(CreateOrderRequest request) throws ParseException {

        String cityCode = getCityIdByCode(request.getFixedLocation().getCityId());
        QueryWrapper<OaSysPlatformTimeControl> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysPlatformTimeControl.CHANNEL_ID, channel);
        queryWrapper.eq(OaSysPlatformTimeControl.CITY_ID, cityCode);
        queryWrapper.eq(OaSysPlatformTimeControl.DELETED, 0);

        List<OaSysPlatformTimeControl> platformTimeControlList = oaSysPlatformTimeRuleMapper.selectList(queryWrapper);
        if (CheckUtil.objIsEmpty(platformTimeControlList)) {
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        //用车时间
        Date startDate = DateUtil.convertStringToDate(request.getUseTime(), "yyyy-MM-dd HH:mm");
        Calendar useCalendar = Calendar.getInstance();
        useCalendar.setTime(startDate);
        //获取用车时间的号数
        int day = useCalendar.get(Calendar.DAY_OF_MONTH);

        //获取当前时间的号数
        Calendar curCalendar = Calendar.getInstance();
        curCalendar.setTime(new Date());
        int curDay = curCalendar.get(Calendar.DAY_OF_MONTH);

        //相差天数
        int differDay = day - curDay;
        if (differDay < 0) {//过时直接拒绝
            return true;
        }
        int useTime = differDay * 60 * 60 * 24 + useCalendar.get(Calendar.HOUR_OF_DAY) * 60 + useCalendar.get(Calendar.MINUTE);

        //请求时间
        Date timestamp = new Date(System.currentTimeMillis());
        Calendar timestampCalendar = Calendar.getInstance();
        timestampCalendar.setTime(timestamp);
        int timestampTime = timestampCalendar.get(Calendar.HOUR_OF_DAY) * 60 + timestampCalendar.get(Calendar.MINUTE);

        for (OaSysPlatformTimeControl info : platformTimeControlList) {
            if (info.getUseFullTime() == 0) {//使用全时就false-->优先判断
                return false;
            } else {
                //开始时间
                Calendar startTime = Calendar.getInstance();
                startTime.setTime(sdf.parse(info.getStartTime()));
                int start = startTime.get(Calendar.HOUR_OF_DAY) * 60 + startTime.get(Calendar.MINUTE);

                //结束时间
                Calendar endTime = Calendar.getInstance();
                endTime.setTime(sdf.parse(info.getEndTime()));
                int end = endTime.get(Calendar.HOUR_OF_DAY) * 60 + endTime.get(Calendar.MINUTE);

                //延长时间
                int delayTime = Integer.parseInt(info.getDelayTime());
                //判断方式为：开始时间≤请求提交时间 ≤结束时间 and 用车时间≤(结束时间（当日）+临近时间长度) == true，即拒绝服务
                if ((start <= timestampTime && timestampTime <= end) && useTime <= (end + delayTime)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public XieChengResponse createOrder(CreateOrderRequest request) {
        //验证平台时间控制是否接单
        try {
            if (verificationTimeByCPrice(request)) {
                return XieChengResponse.error(EXieChengResponseConstant.RROR_EARLY);
            }
        } catch (ParseException e) {
            log.info("验证平台时间 查价异常--->" + e.getMessage());
        }

        CreateOrderResponse response = new CreateOrderResponse();
        //查询是否已经接单，已接单不接了
        Long orderId = request.getCtripPurchaseOrderId();
        OaCOrderPersonal personal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
        if (personal != null) {
            response.wrap(EXieChengResponseConstant.OK);
            response.setVendorOrderId(String.valueOf(personal.getPersonalId()));
            return response;
        }
        String priceMark = request.getPriceMark();
        HashMap<String, String> tprices = redisCommon.getHashMap(RedisPrefixConstant.DIDI_ESTIMATE + priceMark);
        String estimateId = tprices.get(String.valueOf(request.getVehicleType()));
        if (CheckUtil.strIsEmpty(estimateId)) {
            response.wrap(EXieChengResponseConstant.ERROR_NO_PRICEMARK);
            return response;
        }
        String cityId = getCityIdByCode(request.getFixedLocation().getCityId());
        // officeId要根据分单比例产生
        Long officeId = getOfficeId(cityId, EXieChengVehicleType.getByType(request.getVehicleType().intValue()).getValue());
        if (officeId == null || officeId < 1) {
            response.setMessage(EErrorCode.argCheckErr.getDesc());
            return response;
        }

        HashMap<String, Object> priceMap = redisCommon.getHashMap(estimateId);
        if (priceMap == null) {
            response.wrap(EXieChengResponseConstant.ERROR_EXPIRE_PRICEMARK);
            return response;
        }
        Integer robable = (Integer) priceMap.get("robable");
        Long ruleId = Long.parseLong(priceMap.get("ruleId").toString());
        BigDecimal distanceKm = getFee(priceMap, "distanceKm");
        BigDecimal timeCount = getFee(priceMap, "timeCount");
        BigDecimal totalFee = getFee(priceMap, "totalFee");
        //drawFee不再使用询价时计算的费用，现在使用针对每个供应商配置的分成比例来进行计算
        BigDecimal drawFee = getFee(priceMap, "drawFee");
        //BigDecimal drawFee = getDrawFee(officeId, totalFee,cityId);
        BigDecimal startFee = getFee(priceMap, "startFee");
        BigDecimal mileageFee = getFee(priceMap, "mileageFee");
        Long personalId = IDUtil.nextId();
        String phone = request.getPassenger().getLocalPhone();
        String realPhone = request.getPassenger().getMaskRealPhone();
        int plength = realPhone.length();
        String phoneSuffix = realPhone.substring(plength - 4, plength);
        String passengerName = request.getPassenger().getName();

        personal = new OaCOrderPersonal();
        personal.setPassengerName(passengerName);
        personal.setDurationTime(timeCount);
        personal.setMilageDistance(distanceKm);
        personal.setTotalFee(totalFee);
        personal.setDrawFee(drawFee);
        personal.setStartFee(startFee);
        personal.setMileageFee(mileageFee);
        personal.setPersonalId(personalId);
        personal.setIsCarpool(0);
        personal.setRulesId(ruleId);
        personal.setOrderType(EXieChengCallVehType.getByCode(request.getCategoryCode()).getType());
        personal.setOrderStatus(EOrderStatus.waitingResponse.getType());
        personal.setPassengerPhone(phone);
        personal.setPassengerPhoneSuffix(phoneSuffix);
        personal.setOrderChannel(EOrderChannelType.xiecheng.getType());
        //personal.setOrderType(ECallVehType.reservation.getType());
        personal.setAppointment(DateUtil.convertStringToDate(request.getUseTime(), "yyyy-MM-dd HH:mm"));
        personal.setCityId(cityId);
        //数据类型不一样，做映射处理
        personal.setVehicleType(EXieChengVehicleType.getByType(request.getVehicleType().intValue()).getValue());
        personal.setOrderNo(orderId.toString());
        personal.setCreateTime(new Date());
        personal.setCreateUser(passengerName);
        personal.setUpdateTime(new Date());
        personal.setUpdateUser(passengerName);
        //位置信息
        personal.setStartLat(request.getDuseLocation().getLatitude().toString());
        personal.setStartLng(request.getDuseLocation().getLongitude().toString());
        personal.setEndLng(request.getAuseLocation().getLongitude().toString());
        personal.setEndLat(request.getAuseLocation().getLatitude().toString());
        personal.setStartAddress(request.getDuseLocation().getDetailAddress());
        personal.setEndAddress(request.getAuseLocation().getDetailAddress());
        personal.setFlightDate(request.getFlightInfo().getTakeOffTime());
        personal.setFlightDelayTime(request.getFlightInfo().getDepartDelayTime());
        personal.setFlightNo(request.getFlightInfo().getFlightNumber());
        //预估价一口价标识
        personal.setChargeType("0");
        personal.setEstimateId(Long.valueOf(priceMark));
        //添加订单到所在地公司下
        personal.setOfficeId(officeId);
        int insert = oaCOrderPersonalMapper.insert(personal);
        if (insert > 0) {
            // FIXME 正式时使用 producer.sendMsg(personal, MqConstant.BIND_DEFAULT_DRIVER, null, 1);
            producer.sendMsg(personal, MqConstant.BIND_DEFAULT_DRIVER, null, 1);
            //新订单给司管发短信
            producer.sendMsg(personal, MqConstant.NEW_ORDER_TO_MANAGER, null, 1);
            /*OaCOrderPersonal finalPersonal = personal;
            Timer timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                int count = 0;

                @Override
                public void run() {
                    Rv rv = orderStatusSyncService.bindDefaultDriver(finalPersonal);
                    if (rv.isSuc()) {
                        timer.cancel();
                    } else {
                        if (count < 10) {
                            count++;
                        } else {
                            timer.cancel();
                        }
                    }
                }
            };
            timer.schedule(timerTask, 1000, 3000);*/
            OrderInfoCreated orderInfoCreated = OrderInfoCreated.builder().priceMarker(priceMark)
                    .vehicleType(EXieChengVehicleType.getByType(request.getVehicleType().intValue()).getValue())
                    .timestamp(new Date(System.currentTimeMillis()).getTime()).build();
            producer.sendMsg(orderInfoCreated, MqConstant.ORDER_INFO_CREATED, null, 1);
            if (robable == 1) {
                //发送新订单通知
                producer.sendMsg(personal, MqConstant.NOTICE_NEW_ORDER, null, 1);
                //抢单时间为行程开始前两个小时
                long endTime = personal.getAppointment().getTime() - Configuration.DELAY_ROB_BOOKING;
                String bookingKey = RedisPrefixConstant.ORDER_BOOKING + personal.getOfficeId() + ":" + orderId;
                redisCommon.set(bookingKey, JSON.toJSONString(personal));
                redisCommon.addToZSet(RedisPrefixConstant.ORDER_TC_HALL + personal.getCityId(), bookingKey, endTime);
            }

            response.wrap(EXieChengResponseConstant.OK);
            response.setVendorOrderId(String.valueOf(personalId));
            return response;
        } else {
            response.wrap(EXieChengResponseConstant.ERROR);
            return response;
        }
    }

    public Long getOfficeId(String cityCode, Integer rideType) {
        Long officeId = 0L;
        List<OaSysOffice> companysByAdCode = oaSysOfficeMapper.getCompanysByAdCode(cityCode);
        if (CheckUtil.collectionIsEmpty(companysByAdCode))
            return null;
        if (companysByAdCode.size() == 1) {//如果只有一个运力，直接返回
            return companysByAdCode.get(0).getOfficeId();
        }
        Map<String, Integer> drawMap = new HashMap<>();
        for (Iterator<OaSysOffice> oaSysOfficeIterator = companysByAdCode.iterator(); oaSysOfficeIterator.hasNext(); ) {
            OaSysOffice office = oaSysOfficeIterator.next();
            if (CheckUtil.strIsEmpty(office.getExpand1())) {
                continue;
            }
            String[] split = office.getExpand1().split(",")[rideType].split(":");
            String k = office.getOfficeId().toString();
            int v = Integer.valueOf(split[1]);
            drawMap.put(k, v);
        }
        if (CheckUtil.mapIsEmpty(drawMap)) {
            officeId = companysByAdCode.get(0).getOfficeId();
        } else {
            officeId = Long.parseLong(LuckDrawUtil.weightRandom(drawMap));
        }
        return officeId;
    }

    /**
     * 根据公司officeId去查询运力提供商的分成比例进行计算
     *
     * @param officeId
     * @param totalFee
     * @return
     */
    public BigDecimal getDrawFee(Long officeId, BigDecimal totalFee, String cityId) {
        BigDecimal drawFee = new BigDecimal(0);
        BigDecimal percent = new BigDecimal(100);
        QueryWrapper<OaSysBillRuleGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysBillRuleGroup.COMPANY_ID, officeId);
        queryWrapper.eq(OaSysBillRuleGroup.CITY_ID, cityId);
        OaSysBillRuleGroup billGroup = oaSysBillRuleGroupMapper.selectOne(queryWrapper);
        drawFee = totalFee.subtract(totalFee.multiply(new BigDecimal(billGroup.getDrawRatio())).
                divide(percent, 2, RoundingMode.HALF_UP));
        return drawFee;
    }

    @Override
    public XieChengResponse updatePassenger(UpdatePassengerRequest request) {
        UpdatePassengerResponse response = new UpdatePassengerResponse();
        Long orderId = request.getCtripPurchaseOrderId();
        OaCOrderPersonal personal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
        if (personal == null) {
            response.wrap(EXieChengResponseConstant.ERROR);
            return response;
        }

        String phone = request.getPassenger().getLocalPhone();
        String realPhone = request.getPassenger().getMaskRealPhone();
        int plength = realPhone.length();
        String phoneSuffix = realPhone.substring(plength - 4, plength);
        String passengerName = request.getPassenger().getName();

        personal.setPassengerName(passengerName);
        personal.setPassengerPhone(phone);
        personal.setPassengerPhoneSuffix(phoneSuffix);
        personal.setUpdateUser(passengerName);
        personal.setUpdateTime(new Date());
        //int res = oaCOrderPersonalMapper.updateById(personal);
        //取消原有立即update操作改用MQ延迟更新，3级10秒
        producer.sendMsgForDelay(personal, MqConstant.UPDATE_PASSENGER_INFO, null, 3);
        response.wrap(EXieChengResponseConstant.OK);
        return response;
    }

    @Override
    public XieChengResponse queryDriverLocation(QueryDriverLocationRequest request) {
        QueryDriverLocationResponse response = new QueryDriverLocationResponse();
        List<OrderInfoDTO> orders = request.getOrderInfo();

        List<OrderDriverLocationDTO> locations = new ArrayList<>();
        for (OrderInfoDTO order : orders) {
            Long orderId = order.getCtripPurchaseOrderId();
            OrderDriverLocationDTO location = new OrderDriverLocationDTO();
            location.setCtripPurchaseOrderId(orderId);
            location.wrap(EXieChengResponseConstant.ERROR_NO_ORDERID);

            OaCOrderPersonal personal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId)
                    .select(OaCOrderPersonal.DRIVER_ID));
            if (personal != null) {
                location.wrap(EXieChengResponseConstant.ERROR_NO_DRIVER_LOCATION);
                Long driverId = personal.getDriverId();

                String redisKey = RedisPrefixConstant.GPS_VEH_KEY_PREFIX + driverId;
                //log.info("携程获取司机位置redisKey:" + redisKey);
                String string = redisCommon.getStr(redisKey);
                //log.info("携程获取司机位置data:" + string);
                if (string != null) {
                    OaDVehicleGps oaDVehicleGps = JSON.parseObject(string, OaDVehicleGps.class);
                    if (oaDVehicleGps != null) {

                        DriverLocationDTO mlocation = new DriverLocationDTO();
                        mlocation.setLatitude(new BigDecimal(oaDVehicleGps.getLat()));
                        mlocation.setLongitude(new BigDecimal(oaDVehicleGps.getLng()));
                        mlocation.setCoordinate("GCJ02");
                        mlocation.setSpeed(new BigDecimal(oaDVehicleGps.getSpeed()));
                        mlocation.setLocationTime(DateUtil.convertDateToString(oaDVehicleGps.getUpdateTime()));
                        //FIXME 车头朝向怎么处理？
                        mlocation.setDirection(new BigDecimal(0));
                        location.addDriverLocationDTO(mlocation);
                        location.wrap(EXieChengResponseConstant.OK);
                    }
                }
            }
            locations.add(location);
        }
        response.wrap(EXieChengResponseConstant.OK);
        response.setOrderDriverLocationInfo(locations);
        return response;
    }

    @Override
    public XieChengResponse cancelOrder(CancelOrderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();
        response.wrap(EXieChengResponseConstant.ERROR);

        Long orderId = request.getCtripPurchaseOrderId();
        OaCOrderPersonal personal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderId));
        if (personal == null) {
            response.setMessage(EErrorCode.argCheckErr.getDesc());
            return response;
        }
        if (personal.getOrderStatus() == EOrderStatus.cancelOrderNoNeedPayment.getType()) {
            response.wrap(EXieChengResponseConstant.OK);
        } else {
            personal.setOrderStatus(EOrderStatus.cancelOrderNoNeedPayment.getType());
            personal.setCancelReason(request.getCancelReason());
            personal.setUpdateTime(new Date());
            //添加乘客取消时间
            personal.setCancelOrderTime(new Date());

            if (oaCOrderPersonalMapper.updateById(personal) > 0) {
                //更新司机订单状态-->司机已接单需要更新
                if (personal.getDriverId() != null) {//确保乘客订单已指派司机
                    QueryWrapper<OaDOrder> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq(OaDOrder.DRIVER_ID, personal.getDriverId());
                    queryWrapper.eq(OaDOrder.ORDER_NO, personal.getOrderNo());
                    List<OaDOrder> oaDOrderList = oaDOrderMapper.selectList(queryWrapper);
                    for (OaDOrder info : oaDOrderList) {
                        info.setOrderStatus(EOrderStatus.cancelOrderNoNeedPayment.getType());
                        oaDOrderMapper.updateById(info);
                    }
                }

                //删除延时任务所需数据
                String bookingKey = RedisPrefixConstant.ORDER_BOOKING + personal.getOfficeId() + ":" + personal.getOrderNo();
                redisCommon.remove(bookingKey);

                redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_HALL + personal.getCityId(), bookingKey);
                redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET2, bookingKey);
                redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET3, bookingKey);
                redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET4, bookingKey);
                redisCommon.delFromZSet(RedisPrefixConstant.ORDER_TC_ZSET5, bookingKey);

                //删除rediskey
                String key = RedisPrefixConstant.ORDER_OA_D_ORDER + personal.getOrderNo();
                if (redisCommon.hashKey(key)) {
                    if (CheckUtil.objIsNotEmpty(personal.getDriverId())) {
                        redisCommon.remove(RedisPrefixConstant.ORDER_VEH + personal.getDriverId());
                    }
                    if (CheckUtil.objIsNotEmpty(personal.getUserId())) {
                        redisCommon.remove(RedisPrefixConstant.ORDER_USER + personal.getUserId());
                    }
                    redisCommon.remove(key);
                }
                response.wrap(EXieChengResponseConstant.OK);
            }
        }
        return response;
    }

    @Override
    public XieChengResponse pushVehicleInfo(PushVehicleInfoRequest request) {
        PushVehicleInfoResponse response = new PushVehicleInfoResponse();
        response.wrap(EXieChengResponseConstant.ERROR);

        int res = 0;
        List<VehicleInfoDTO> vehicleInfos = request.getData();
        for (VehicleInfoDTO vehicleInfo : vehicleInfos) {
            //检查有无该信息
            res = vehicleInfoMapper.getCountById(vehicleInfo.getVehicleId());
            if (res <= 0) {
                res = vehicleInfoMapper.insert(vehicleInfo);
            }
            if (res < 1) {
                return response;
            }
        }
        response.wrap(EXieChengResponseConstant.OK);
        return response;
    }

    @Override
    public XieChengResponse pushCityInfo(PushCityInfoRequest request) {
        PushCityInfoResponse response = new PushCityInfoResponse();
        response.wrap(EXieChengResponseConstant.ERROR);

        int res = 0;
        List<CityInfoDTO> cityInfos = request.getData();
        for (CityInfoDTO cityInfo : cityInfos) {
            //检查有无信息
            res = cityInfoMapper.getCountById(cityInfo.getCityId());
            if (res <= 0) {
                res = cityInfoMapper.insert(cityInfo);
            }
            if (res < 1) {
                return response;
            }
        }
        response.wrap(EXieChengResponseConstant.OK);
        return response;
    }

    private String getCityIdByCode(String code) {
        switch (code) {
            case "1": {
                //北京
                return "110100";
            }
            case "2": {
                //上海
                return "310100";
            }
            case "12": {
                //南京
                return "320100";
            }
            case "28": {
                //成都
                return "510100";
            }
            case "42": {
                //海口
                return "460100";
            }
            case "91": {
                //九寨沟
                return "513200";
            }
            case "158": {
                //长春
                return "220100";
            }
            case "39": {
                //乌鲁木齐
                return "650100";
            }
            case "43": {
                //三亚
                return "460200";
            }
            case "15": {
                //扬州
                return "321000";
            }
            case "529": {
                //伊宁
                return "654002";
            }
            case "150": {
                //牡丹江
                return "231000";
            }
            case "3": {
                return "120100";
            }
            //连云港
            case "353": {
                return "320700";
            }
        }
        return null;
    }

    private BigDecimal getFee(HashMap<String, Object> map, String key) {
        Object object = map.get(key);
        if (object == null) {
            return new BigDecimal(0);
        }
        if (object instanceof BigDecimal) {
            return (BigDecimal) object;
        } else {
            return new BigDecimal(object.toString());
        }
    }

    private String sendToXC(int type, String orderId, String body) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = sdf.format(System.currentTimeMillis());
        log.info("XC-" + body);

        String params = "";
        try {
            params = XieChengUtil.encodeDES(secretKey, body);
            params = params.toUpperCase();
            log.info("XC-" + params);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        String sign = XieChengUtil.getCallbackSign(venderId, timeStamp, params.length(), secretKey);
        log.info("XC-" + sign);

        String action = "";
        switch (type) {
            case 1: {
                //订单确认接口
                action = "order/confirm";
            }
            break;
            case 2: {
                //司机信息推送接口
                action = "driver/push";
            }
            break;
            case 3: {
                //司机状态推送接口
                action = "driver/inplace";
            }
            break;
            case 4: {
                //订单完成接口
                action = "order/complete";
            }
            break;
            case 5: {
                //订单详情接口
                action = "order/detail";
            }
            break;
            default: {
                return null;
            }
        }
        String url = callback + "/" + channel2 + "-" + venderId + "/" + action + "/" + version + "/" + orderId + "/" + timeStamp + "/" + sign;
        String result = null;
        try {
            log.info("XC-" + url);
            result = HttpRequestUtil.requestPostJson(url, params);
            log.info("XC-" + result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public HashMap verifyAreaCode(GouldResult.RouteBean router, String cityCode, int callType, int channel, String origin, String destination) {
        HashMap<Object, Object> reMap = new HashMap();
        //调用高德接口
        String sAdCode = router.getSAcode();
        String eAdCode = router.getEAcode();

        //  判断起点和终点是否包含数据库中的stationKeyword 返回该rulesNo
        Integer rulesNo = getRulesNo(origin, destination, cityCode, callType);

        //数据库或redis中查询禁行区设置,不区分运力类型
        List<NewBillRules> reMap1 = embargoAreaService.getPriceDetail(channel, cityCode, callType, rulesNo);
        List<RulesParam> fees = JSON.parseArray(reMap1.get(0).getJsonRules(), RulesParam.class);
        reMap1.get(0).setFees(fees);
        List<RulesParam> rulesParamList = fees;
        reMap.put("rules", reMap1);
        Iterator<RulesParam> rulesParamIterator = rulesParamList.iterator();
        while (rulesParamIterator.hasNext()) {
            RulesParam rulesParam = rulesParamIterator.next();
            List<OaSysBillRuleNewEmbargoMini> em = rulesParam.getRuleEmbargos();
            for (int i = 0; i < em.size(); i++) {
                OaSysBillRuleNewEmbargoMini embargoMini = em.get(i);
                int veTpe = ETongChengRideType.getById(rulesParam.getVehicleType()).getValue();
                //判断禁运起点和目的地勾选情况
                int refuseType = embargoMini.getRefuseType();
                int flag;
                if (refuseType == 0) {
                    //起点在其中则禁运
                    flag = 0;
                } else if (refuseType == 1) {
                    //终点禁运
                    flag = 1;
                } else if (refuseType == 2) {  //0 and 1终点禁运
                    // 终点或起点在其中
                    flag = 2;
                } else if (refuseType == 3) {
                    //起点和终点都在其中则禁运
                    flag = 3;
                } else if (refuseType == 4) {
                    //无禁运
                    flag = 4;
                } else {
                    //默认无禁运
                    flag = 4;
                }
                int areaLevel = embargoMini.getAreaLevel();//地区等 省、市、县区
                boolean verifiedValue = verifyArea(embargoMini.getAreaCode(), sAdCode, eAdCode, areaLevel, flag);
                if (veTpe == 0) {//经济型
                    if (verifiedValue) {//如果判断为true，则说明命中禁运区域
                        reMap.put(veTpe, 1);
                        break;
                    } else {
                        reMap.put(veTpe, 0);
                    }
                } else if (veTpe == 1) {//舒适性
                    if (verifiedValue) {//如果判断为true，则说明命中禁运区域
                        reMap.put(veTpe, 1);
                        break;
                    } else {
                        reMap.put(veTpe, 0);
                    }
                } else if (veTpe == 2) {//商务型
                    if (verifiedValue) {//如果判断为true，则说明命中禁运区域
                        reMap.put(veTpe, 1);
                        break;
                    } else {
                        reMap.put(veTpe, 0);
                    }
                } else if (veTpe == 3) {//豪华型
                    if (verifiedValue) {//如果判断为true，则说明命中禁运区域
                        reMap.put(veTpe, 1);
                        break;
                    } else {
                        reMap.put(veTpe, 0);
                    }
                }

            }
        }
        return reMap;
    }

    private Integer getRulesNo(String origin, String destination, String cityCode, int callType) {
        Integer stationKind = 0;
        Integer rulesNo = null;
        if (callType == 3 || callType == 4) {
            stationKind = 1;
        }
        if (callType == 5 || callType == 6) {
            stationKind = 2;
        }
        QueryWrapper<OaSysBillSpecialSceneRule> sceneRuleQueryWrapper = new QueryWrapper<>();
        sceneRuleQueryWrapper.eq(OaSysBillSpecialSceneRule.CITY_CODE, cityCode);
        sceneRuleQueryWrapper.eq(OaSysBillSpecialSceneRule.STATION_KIND, stationKind);
        List<OaSysBillSpecialSceneRule> specialSceneRules = oaSysBillSpecialSceneRuleMapper.selectList(sceneRuleQueryWrapper);
        if (CheckUtil.objIsNotEmpty(specialSceneRules)) {
            for (OaSysBillSpecialSceneRule oaBillScene : specialSceneRules
            ) {
                String stationKeyword = oaBillScene.getStationKeyword();
                //如果是接机或接站 判断终点中是否包含keyword
                if ((callType == 3 || callType == 5) && destination.contains(stationKeyword)) {
                    rulesNo = oaBillScene.getRulesNo();
                }
                //如果是送机或送站 判断起点中是否包含keyword
                else if ((callType == 4 || callType == 6) && origin.contains(stationKeyword)) {
                    rulesNo = oaBillScene.getRulesNo();
                }
            }
        }
        return rulesNo;
    }

    /**
     * @param sAdCode   高德获取的起点adcode
     * @param eAdCode   高德获取的终点adcode
     * @param areaLevel 数据库保存的行政区划等级
     * @param flag      起点终点禁运情况
     * @return
     */
    public boolean verifyArea(String adcode, String sAdCode, String eAdCode, int areaLevel, int flag) {
        boolean r = false;
        if (flag == 4) { //不禁运直接返回
            return r;
        }
        String al = "";
        if (areaLevel == 0) {//省、直辖市
            //判断行政编吗前两位
            al = adcode.substring(0, 2);
            r = verifyAreaType(al, flag, sAdCode, eAdCode);
        } else if (areaLevel == 1) {//市级
            //市级判断前4位
            al = adcode.substring(0, 4);
            r = verifyAreaType(al, flag, sAdCode, eAdCode);
        } else if (areaLevel == 2) {//区县级
            //区县精确对比
            al = String.valueOf(adcode);
            r = verifyAreaType(al, flag, sAdCode, eAdCode);
        }
        return r;
    }

    public boolean verifyAreaType(String al, int flag, String sAdCode, String eAdCode) {
        boolean r = false;
        if (flag == 0) {//起点是否在禁运区域
            r = sAdCode.startsWith(al);
        } else if (flag == 1) {//终点是否在禁运区域
            r = eAdCode.startsWith(al);
        } else if (flag == 2) {//起点或终点是否在禁运区域
            r = sAdCode.startsWith(al) || eAdCode.startsWith(al);
        } else if (flag == 3) {//起点和终点是否在禁运区域
            r = sAdCode.startsWith(al) && eAdCode.startsWith(al);
        }
        return r;
    }

    public static void main(String[] args) {
        Date startDate = DateUtil.convertStringToDate("2021-06-06 00:00", "yyyy-MM-dd HH:mm");
        Calendar useCalendar = Calendar.getInstance();
        useCalendar.setTime(startDate);
        //获取用车时间的号数
        //int day = useCalendar.get(Calendar.DAY_OF_MONTH);
        double day = useCalendar.getTimeInMillis() / (3600 * 24 * 1000D);
        //获取当前时间的号数
        Calendar curCalendar = Calendar.getInstance();
        curCalendar.setTime(DateUtil.convertStringToDate("2021-06-05 23:59", "yyyy-MM-dd HH:mm"));
        //int curDay = curCalendar.get(Calendar.DAY_OF_MONTH);
        double curDay = curCalendar.getTimeInMillis() / (3600 * 24 * 1000D);
        double differDay = day - curDay;
        if (differDay < 0) {//过时直接拒绝
            //return true;
            System.out.println(differDay);
        }
        long useTime = useCalendar.get(Calendar.HOUR_OF_DAY) * 60 + useCalendar.get(Calendar.MINUTE);// tmpTime/(1000*60);
        double value = differDay * 24 * 60;
        System.out.println(useTime + value);
    }

}
